import { invoke } from "@tauri-apps/api/core";
import { ConnectionOptions, Message, MessageTransaction, MessageValue, Preference, ReceivedSecondaryMessage, SMLFile, SMLResult } from "./types";
import { SyncTransactionAction } from "./enums";

const smlService = {
    // sml_load
    load: (id: number, path: string | null): Promise<SMLFile> => {
        return invoke<SMLFile>("sml_load", { id: id, path: path })
    },
    syncTransaction: (id: number, txId: string, transaction: MessageTransaction, action: SyncTransactionAction): Promise<string> => {
        return invoke<string>("sml_sync_transaction", { id: id, txId: txId, transaction: transaction, action })
    },
    delTransaction: (id: number, txId: string): Promise<any> => {
        return invoke("sml_del_transaction", { id: id, txId: txId })
    },
    swapTransaction: (id: number, fromTxId: string, toTxId: string): Promise<any> => {
        return invoke("sml_swap_transaction", { id: id, fromTxId, toTxId })
    },
    save: (id: number, path: string | null) => {
        return invoke<void>("sml_save", { id: id, path: path })
    },
    getConfiguration: (id: number): Promise<SMLResult<ConnectionOptions>> => {
        return invoke("sml_get_configuration", { id: id })
    },
    setConfiguration: (id: number, configuration: ConnectionOptions): Promise<void> => {
        return invoke("sml_set_configuration", { id: id, configuration })
    },
    getPreference: (id: number): Promise<SMLResult<Preference>> => {
        return invoke<SMLResult<Preference>>("sml_get_preference", { id: id })
    },
    setPreference: (id: number, preference: Preference): Promise<void> => {
        return invoke("sml_set_preference", { id: id, preference })
    },
    openLogDir: (id: number) => {
        return invoke("sml_open_log_dir", { id })
    }
};

const connectionService = {
    create: (path: string|null) => {
        return invoke<number>("create_connection", { path });
    },
    remove: (id: number) => {
        return invoke<number>("remove_connection", { id });
    }
}

const secsService = {
    connect: (id: number) => {
        return invoke<void>("secs_connect", { id: id });
    },
    shutdown: (id: number) => {
        return invoke<void>("secs_shutdown", { id: id });
    },
    send_primary: (id: number, txId: string) => {
        return invoke<ReceivedSecondaryMessage | null>("secs_send_primary", { id: id, txId });
    },
    copyMessageText: (message: Message) => {
        return invoke<void>("secs_copy_message_text", { message });
    },
    copyValueText: (value: MessageValue) => {
        return invoke<void>("secs_copy_value_text", { value });
    }
}

export { smlService, connectionService, secsService }